package com.thfw.test.view.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bigkoo.pickerview.TimePickerView;
import com.github.gzuliyujiang.calendarpicker.CalendarPicker;
import com.github.gzuliyujiang.calendarpicker.OnRangeDatePickListener;
import com.github.gzuliyujiang.calendarpicker.OnSingleDatePickListener;
import com.thfw.wmd.R;
import com.thfw.test.model.authManage.AuthBaseBean;
import com.thfw.test.model.bean.EnergyBean;
import com.thfw.test.model.bean.RegionBean;
import com.thfw.test.utils.ConfigurationEntry;
import com.thfw.test.utils.StringUtils;
import com.thfw.test.view.network.AuthManageService;
import com.thfw.test.view.widget.LineChart02View;


import org.xclcharts.chart.LineData;
import org.xclcharts.renderer.XEnum;

import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import scooper.cn.sc_base.log.SCLog;
import utils.RetrofitWrapper;

/**
 * Created BY Cuishikun
 * Created ON 2021/11/15
 * Package Name com.thfw.test.view.fragment
 **/
public class EnergyManagementFragment extends BaseFragment {


    private static final String TAG = EnergyManagementFragment.class.getCanonicalName();
    LineChart02View view1;
    LineChart02View view2;
    @BindView(R.id.tv_day_energy)
    TextView tv_day_energy;
    @BindView(R.id.top_buttons)
    protected RadioGroup topButtons;
    @BindView(R.id.tv_pickdate1)
    TextView tv_pickdate1;
    @BindView(R.id.tv_pickdate2)
    TextView tv_pickdate2;
    @BindView(R.id.btn_search)
    Button btn_search;
    int searchType = 0;
    String host;
    int port;
    boolean isFirst;

    public static EnergyManagementFragment newInstance() {
        EnergyManagementFragment fragment = new EnergyManagementFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fm_energy_managment;
    }


    @Override
    protected void initView() {

        view1 = rootView.findViewById(R.id.linechart1);
        view2 = rootView.findViewById(R.id.linechart2);

        host = getConfig().getString(ConfigurationEntry.HOST, "192.168.161.121");
        port = getConfig().getInt(ConfigurationEntry.PORT, 8080);
        tv_day_energy.setText(getConfig().getString(ConfigurationEntry.TODAY_ENERGY,"0KW"));


        topButtons.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (checkedId == R.id.rb_day) {
                    searchType = 0;
                    tv_pickdate2.setText(tv_pickdate1.getText().toString());
                } else if (checkedId == R.id.rb_month) {
                    searchType = 1;
                } else if (checkedId == R.id.rb_year) {
                    searchType = 2;
                }
            }
        });


        tv_pickdate1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickDate(tv_pickdate1, tv_pickdate2);
            }
        });

        tv_pickdate2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickDate(tv_pickdate2, tv_pickdate1);
            }
        });

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getEnergyData();
            }
        });

        if(isFirst){
            view1.chartLabels(13, 2);
            LinkedList<Double> dataSeries1 = new LinkedList<Double>();
            dataSeries1.add(10d);
            dataSeries1.add(30d);
            dataSeries1.add(50d);
            dataSeries1.add(120d);
            dataSeries1.add(180d);
            dataSeries1.add(290d);
            dataSeries1.add(400d);
            dataSeries1.add(850d);
            dataSeries1.add(980d);
            dataSeries1.add(1360d);
            dataSeries1.add(1420d);
            dataSeries1.add(1960d);
            LineData lineData1 = new LineData("今日累计能耗", dataSeries1, Color.rgb(234, 83, 71));
            lineData1.setDotRadius(5);
            lineData1.setDotStyle(XEnum.DotStyle.DOT);

            //Line 2
            LinkedList<Double> dataSeries2 = new LinkedList<Double>();
            dataSeries2.add(90d);
            dataSeries2.add(120d);
            dataSeries2.add(180d);
            dataSeries2.add(210d);
            dataSeries2.add(230d);
            dataSeries2.add(240d);
            dataSeries2.add(330d);
            dataSeries2.add(500d);
            dataSeries2.add(590d);
            dataSeries2.add(860d);
            dataSeries2.add(920d);
            dataSeries2.add(1060d);

            LineData lineData2 = new LineData("昨日累计能耗", dataSeries2, Color.rgb(75, 166, 51));
            lineData2.setDotRadius(5);
            lineData2.setDotStyle(XEnum.DotStyle.DOT);

            ArrayList<LineData> list = new ArrayList<>();
            list.add(lineData1);
            list.add(lineData2);
            view1.getChar().getDataAxis().setAxisMax(2000);         //数据轴最大值
            //数据轴刻度间隔
            view1.getChar().setTitle("今日昨日能耗累计对比图");
            view1.getChar().addSubtitle("单位 KW·H ");
            view1.getChar().getDataAxis().setAxisSteps(100);
            view1.setCharData(list);
            view1.chartRender();
            view1.initView();

        }


        //先做假数据封装折线图1

//        getEnergyData();

    }

    @Override
    protected void firstCreate() {

        isFirst = true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isFirst = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        view1.cancelThread();
//        view2.cancelThread();
    }


    //能耗获取
    LineData lineData;
    LinkedList<Double> dataSeries = null;
    private void getEnergyData() {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");

            Map<String, String> params = new HashMap<>();
            params.put("type", searchType + "");
            if (searchType == 0) {
                params.put("createTime", tv_pickdate1.getText().toString());
            } else {
                params.put("startTime", tv_pickdate1.getText().toString());
                params.put("endTime", tv_pickdate2.getText().toString());
            }


            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).getEnergyData(token, params).enqueue(new Callback<AuthBaseBean<EnergyBean>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<EnergyBean>> call, Response<AuthBaseBean<EnergyBean>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());

                    if (response!=null && response.body()!=null && response.body().getData() != null) {
                        //设置底部栏
                        EnergyBean bean1 = response.body().getData();
                        ArrayList<LineData> list2 = new ArrayList<>();
                        for (EnergyBean.RegionEnergyBean bean : response.body().getData().getRegionEnergy()) {
                            if (bean != null) {
                                 dataSeries = new LinkedList<Double>();
                                for (EnergyBean.RegionEnergyBean.Bean item : bean.getEnergy()) {
                                    if(item.getElEnergy()!=null){
                                        dataSeries.add(Double.valueOf(item.getElEnergy()));
                                    }else{
                                        dataSeries.add(Double.valueOf(1));
                                    }
                                }

                                lineData = new LineData(bean.getRegion(), dataSeries
                                        , Color.rgb(new Double(255 * Math.random()).intValue()
                                        , new Double(255 * Math.random()).intValue()
                                        , new Double(255 * Math.random()).intValue()));

                                lineData.setDotRadius(5);
                                lineData.setDotStyle(XEnum.DotStyle.DOT);
                            }
                            list2.add(lineData);
                        }
                        view1.getChar().getDataAxis().setAxisSteps(200 );
                        view1.chartLabels(bean1.getTime());
                        view1.getChar().getDataAxis().setAxisMax(Collections.max(dataSeries)+300);
                        switch (searchType){
                            case 0:
                                view1.getChar().setTitle(tv_pickdate1.getText().toString()+"日能耗累计对比图");
                                break;
                            case 1:
                                view1.getChar().setTitle(tv_pickdate1.getText().toString()+"至"+tv_pickdate2.getText().toString()+"月度能耗累计对比图");
                                break;
                            case 2:
                                view1.getChar().setTitle(tv_pickdate1.getText().toString()+"至"+tv_pickdate2.getText().toString()+"年度能耗累计对比图");
                                break;
                        }
                        view1.clearData();
                        view1.setCharData(list2);
                        view1.chartRender();
                        view1.refreshChart();
                        view1.reDraw();
                    }else {
                        Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<AuthBaseBean<EnergyBean>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());

                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void pickDate(TextView tv, TextView tv2) {
        TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String datef = sdf.format(date);
                if (searchType == 0) {
                    tv.setText(datef);
                    tv2.setText(datef);
                } else {
                    tv.setText(datef);
                }
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字

                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

        pvTime.show();
    }

}